package com.saxon.system.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.saxon.system.constant.HttpStatus;
import com.saxon.system.pojo.SysAuthUser;
import com.saxon.system.utils.AjaxResult;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class JWTTokenFilter extends AbstractAuthenticationProcessingFilter {

    public JWTTokenFilter (String defaultFilterProcessesUrl, AuthenticationManager authenticationManager) {
        super (new AntPathRequestMatcher (defaultFilterProcessesUrl));
        setAuthenticationManager (authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication (HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        SysAuthUser sysAuthUser = new ObjectMapper ().readValue (request.getInputStream (), SysAuthUser.class);
        System.out.println ("进入验证jwt-token 1111=============");
        return getAuthenticationManager ().authenticate (new UsernamePasswordAuthenticationToken (sysAuthUser.getUsername (), sysAuthUser.getPassword ()));
    }

    /**
     * 成功返回信息
     *
     * @param request    请求
     * @param response   响应
     * @param chain      链式
     * @param authResult 认证结果
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication (HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities ();
        List<String> collect = authorities.stream ().map (authority -> authorities.toString ()).collect (Collectors.toList ());
        System.out.println ("进入验证jwt-token");
        String auth = JWT.create ()
                //设置权限
                .withClaim ("authorities", collect)
                .withSubject (authResult.getName ())
                .withExpiresAt (new Date (System.currentTimeMillis () + 10 * 60 * 1000))
                .sign (Algorithm.HMAC256 ("sss"));
        response.setStatus (HttpStatus.SUCCESS);
    }

    @Override
    protected void unsuccessfulAuthentication (HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        AjaxResult.error (HttpStatus.UNAUTHORIZED, "登陆失败");
    }
}
